import pygame
from pytmx import load_pygame

from Action.Create_sprite import create_sprite
from Game import SCREEN_HALF_WIDTH, SCREEN_HALF_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT


def boundary(x, y):
    view_x = x - SCREEN_HALF_WIDTH
    view_y = y - SCREEN_HALF_HEIGHT
    if view_x < 0:
        view_x = 0

    if view_y < 0:
        view_y = 0

    if view_x >= 2800 - SCREEN_WIDTH:
        view_x = 2800 - SCREEN_WIDTH - 1
    if view_y >= 1200 - SCREEN_HEIGHT:
        view_y = 1200 - SCREEN_HEIGHT - 1
    return view_x, view_y


def step8_create_sprite():
    """
    step8: 创建人物精灵
    :return:
    """
    # 初始化pygame
    pygame.init()
    # 获取游戏时钟
    clock = pygame.time.Clock()
    # 创建游戏的窗口 640 * 236 根据要显示图片的大小设置
    screen = pygame.display.set_mode((1280, 720), 0, 32)
    # 加载图片文件
    background = pygame.image.load("../Resources/tmx/map2-1.png")
    tiled_map_data = load_pygame("../Resources/tmx/map2.tmx")
    obstacle_group = pygame.sprite.Group()
    japanese_group = pygame.sprite.Group()
    prizes_group = pygame.sprite.Group()
    yu_er, captain, vice_captain = create_sprite(tiled_map_data, obstacle_group, japanese_group, prizes_group)
    while True:
        # 游戏循环
        for event in pygame.event.get():
            # 关闭事件，进行退出处理
            if event.type == pygame.QUIT:
                exit()
            elif event.type == pygame.KEYDOWN:
                yu_er.run(event.key)
        view_x, view_y = boundary(yu_er.pos_x, yu_er.pos_y)
        # 绘制图片到显示窗口
        sub_view = background.subsurface((view_x, view_y, SCREEN_WIDTH, SCREEN_HEIGHT))
        screen.blit(sub_view, (0, 0))
        yu_er.draw(screen, view_x, view_y)
        captain.draw(screen)
        vice_captain.draw(screen)
        for japanese in japanese_group:
            japanese.draw(screen)
            japanese.run()
        clock.tick(20)
        # 调用flip方法更新显示,也可以使用update方法
        pygame.display.flip()


if __name__ == "__main__":
    step8_create_sprite()
